package org.springblade.mach.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.jsonwebtoken.lang.Collections;
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springblade.common.cache.DictCache;
import org.springblade.common.enums.DictEnum;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.utils.*;
import org.springblade.flow.engine.vo.FlowProcessVO;
import org.springblade.mach.entity.*;
import org.springblade.mach.excel.DrawingWorkOrderExcel;
import org.springblade.mach.service.*;
import org.springblade.mach.utils.ExcelUtils;
import org.springblade.mach.vo.DrawingBomKey;
import org.springblade.mach.vo.DrawingWorkOrderQueryVO;
import org.springblade.mach.vo.DrawingWorkOrderVO;
import org.springblade.modules.resource.builder.oss.OssBuilder;
import org.springblade.modules.resource.entity.Attach;
import org.springblade.modules.resource.entity.Oss;
import org.springblade.modules.resource.service.IAttachService;
import org.springblade.modules.resource.vo.AttachVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DrawingWorkOrderServiceImpl implements IDrawingWorkOrderService {

	@Autowired
	private IDrawingUploadService drawingUploadService;

	@Autowired
	private IAttachService attachService;

	// 对象存储构建类
	@Autowired
	private OssBuilder ossBuilder;

	@Autowired
	private ExcelUtils excelUtils;

	@Autowired
	private IDrawingInfoService drawingInfoService;

	@Autowired
	private IDrawingInfoNodeService drawingInfoNodeService;

	@Autowired
	private IProjectManaService projectManaService;

	@Autowired
	private IDrawingInfoAttachService drawingInfoAttachService;

	@Override
	public IPage<DrawingWorkOrderVO> getDrawingWordOrder(DrawingWorkOrderQueryVO workOrderQuery, Query pageQuery) {
		// 统计物料清单列表
		List<DrawingWorkOrderVO> workOrderList = findMaterielBomDev(workOrderQuery);
		// 自定义实现分页
		IPage<DrawingWorkOrderVO> page = Condition.getPage(pageQuery);
		if (CollectionUtil.isEmpty(workOrderList)) {
			page.setTotal(0);
			page.setRecords(workOrderList);
		} else {
			page.setTotal(workOrderList.size());
			int fromIndex = (int) ((page.getCurrent() - 1) * page.getSize());
			int toIndex = (int) page.getSize();
			if ((int) page.getCurrent() != 1) {
				if (workOrderList.size() - fromIndex > page.getSize()) {
					toIndex = (int) page.getSize() * (int) page.getCurrent();
				} else {
					toIndex = workOrderList.size();
				}
			} else {
				if (workOrderList.size() < toIndex) {
					toIndex = workOrderList.size();
				}
			}
			List<DrawingWorkOrderVO> workOrderVOList = workOrderList.subList(fromIndex, toIndex);
			page.setRecords(workOrderVOList);
		}
		return page;
	}

	@Override
	public void downloadMaterielBom(DrawingWorkOrderQueryVO workOrderQuery, HttpServletResponse response) {
		// 统计物料清单列表(正式环境)
//		List<DrawingWorkOrderVO> workOrderList = findMaterielBom(workOrderQuery);
		// 测试环境中多个参数
		List<DrawingWorkOrderVO> workOrderList = findMaterielBomDev(workOrderQuery);
		// 封装Excel数据
		List<DrawingWorkOrderExcel> workOrderExcelList = new ArrayList<>();
		for (DrawingWorkOrderVO workOrderVO : workOrderList) {
			DrawingWorkOrderExcel workOrderExcel = new DrawingWorkOrderExcel();
			BeanUtil.copy(workOrderVO, workOrderExcel);
			workOrderExcelList.add(workOrderExcel);
		}

		// 导出物料清单
		ExcelUtil.export(response, DictCache.getValue("bill_type", workOrderQuery.getBillType()) + DateUtil.time(),
			DictCache.getValue("bill_type", workOrderQuery.getBillType()), workOrderExcelList, DrawingWorkOrderExcel.class);

	}

	// 正式环境中使用的
	private List<DrawingWorkOrderVO> findMaterielBom(DrawingWorkOrderQueryVO workOrderQuery) {
		if (workOrderQuery == null) {
			throw new ServiceException("参数不能为空!");
		}
		if (workOrderQuery.getBillType() == null) {
			throw new ServiceException("单据类型不能为空!");
		}
		if (StringUtil.isEmpty(workOrderQuery.getWorkOrderNo()) && StringUtil.isEmpty(workOrderQuery.getDrawingNumberList())) {
			throw new ServiceException("请输入要查询的工单号或设备编号!");
		}

		List<DrawingWorkOrderVO> workOrderList = new ArrayList<>();
		if (StringUtil.isNotBlank(workOrderQuery.getWorkOrderNo()) && StringUtil.isNotBlank(workOrderQuery.getDrawingNumber())) {
			// 工单下设备信息
			ProjectMana projectMana = projectManaService.getProjectManaDetail(workOrderQuery.getWorkOrderNo(), workOrderQuery.getDrawingNumber());
			if (projectMana == null) {
				throw new ServiceException("项目工单和图纸编号不匹配，请重新输入!");
			}
			if (workOrderQuery.getBillType() != 5 && workOrderQuery.getBillType() != 6) {
				workOrderList = handleBomExcel(workOrderQuery.getBillType(), workOrderQuery.getWorkOrderNo(), projectMana.getDesignNumber());
			} else {
				workOrderList = this.findAllLevelList(workOrderQuery.getBillType(), workOrderQuery.getWorkOrderNo(), projectMana.getDesignNumber());
			}
		} else if (StringUtil.isNotBlank(workOrderQuery.getWorkOrderNo())) {
			QueryWrapper<ProjectMana> queryWrapper = Condition.getQueryWrapper(new ProjectMana());
			queryWrapper.lambda().eq(ProjectMana::getWorkOrderNo, workOrderQuery.getWorkOrderNo());
			ProjectMana projectMana = projectManaService.getOne(queryWrapper);
			if (projectMana == null) {
				throw new ServiceException("数据不存在，请重新输入!");
			}
			if (workOrderQuery.getBillType() != 5 && workOrderQuery.getBillType() != 6) {
				workOrderList = handleBomExcel(workOrderQuery.getBillType(), projectMana.getWorkOrderNo(), projectMana.getDesignNumber());
			} else {
				workOrderList = this.findAllLevelList(workOrderQuery.getBillType(), workOrderQuery.getWorkOrderNo(), projectMana.getDesignNumber());
			}

		} else if (StringUtil.isNotBlank(workOrderQuery.getDrawingNumber())) {
			//校验设备编号
			QueryWrapper<DrawingInfo> queryWrapper = Condition.getQueryWrapper(new DrawingInfo());
			queryWrapper.lambda().eq(DrawingInfo::getDrawingNumber, workOrderQuery.getDrawingNumber());
			DrawingInfo drawingInfo = drawingInfoService.getOne(queryWrapper);
			if (drawingInfo == null) {
				throw new ServiceException("数据不存在，请重新输入!");
			}
			if (workOrderQuery.getBillType() != 5 && workOrderQuery.getBillType() != 6) {
				workOrderList = handleBomExcel(workOrderQuery.getBillType(), workOrderQuery.getWorkOrderNo(), drawingInfo.getDrawingNumber());
			} else {
				workOrderList = this.findAllLevelList(workOrderQuery.getBillType(), workOrderQuery.getWorkOrderNo(), drawingInfo.getDrawingNumber());
			}
		}
		return workOrderList;
	}

	// 测试环境中使用
	private List<DrawingWorkOrderVO> findMaterielBomDev(DrawingWorkOrderQueryVO workOrderQuery) {
		if (workOrderQuery == null) {
			throw new ServiceException("参数不能为空!");
		}
		if (workOrderQuery.getBillType() == null) {
			throw new ServiceException("单据类型不能为空!");
		}
		if (StringUtil.isEmpty(workOrderQuery.getWorkOrderNo()) && StringUtil.isEmpty(workOrderQuery.getDrawingNumberList())) {
			throw new ServiceException("请输入要查询的工单号或设备编号!");
		}

		List<DrawingWorkOrderVO> workOrderList = new ArrayList<>();
		if (StringUtil.isNotBlank(workOrderQuery.getWorkOrderNo()) && StringUtil.isNotBlank(workOrderQuery.getDrawingNumber())) {
			// 工单下设备信息
			ProjectMana projectMana = projectManaService.getProjectManaDetail(workOrderQuery.getWorkOrderNo(), workOrderQuery.getDrawingNumber());
			if (projectMana == null) {
				throw new ServiceException("项目工单和图纸编号不匹配，请重新输入!");
			}
			if (workOrderQuery.getBillType() != 5 && workOrderQuery.getBillType() != 6) {
				workOrderList = handleBomExcel(workOrderQuery.getBillType(), workOrderQuery.getWorkOrderNo(), projectMana.getDesignNumber());
			} else {
				workOrderList = this.findAllLevelList(workOrderQuery.getBillType(), workOrderQuery.getWorkOrderNo(), projectMana.getDesignNumber());
			}
		} else if (StringUtil.isNotBlank(workOrderQuery.getWorkOrderNo())) {
			QueryWrapper<ProjectMana> queryWrapper = Condition.getQueryWrapper(new ProjectMana());
			queryWrapper.lambda().eq(ProjectMana::getWorkOrderNo, workOrderQuery.getWorkOrderNo());
			ProjectMana projectMana = projectManaService.getOne(queryWrapper);
			if (projectMana == null) {
				throw new ServiceException("数据不存在，请重新输入!");
			}
			if (workOrderQuery.getBillType() != 5 && workOrderQuery.getBillType() != 6) {
				workOrderList = handleBomExcel(workOrderQuery.getBillType(), projectMana.getWorkOrderNo(), projectMana.getDesignNumber());
			} else {
				workOrderList = this.findAllLevelList(workOrderQuery.getBillType(), workOrderQuery.getWorkOrderNo(), projectMana.getDesignNumber());
			}
		} else if (!Collections.isEmpty(workOrderQuery.getDrawingNumberList())) {
			//校验设备编号
			List<DrawingInfo> drawingInfoList = drawingInfoService.list(new QueryWrapper<DrawingInfo>()
				.lambda()
				.in(DrawingInfo::getDrawingNumber, workOrderQuery.getDrawingNumberList()));
			for (DrawingInfo drawingInfo : drawingInfoList) {
				if (drawingInfo == null) {
					throw new ServiceException("数据 " + drawingInfo.getDrawingNumber() + " 不存在，请重新输入!");
				}
			}

			List<String> drawingNumberList = drawingInfoList.stream().map(DrawingInfo::getDrawingNumber).collect(Collectors.toList());
			//  单据类型(1-4 04一层)
			if (workOrderQuery.getBillType() != 5 && workOrderQuery.getBillType() != 6) {
				try {
					workOrderList = this.handleBomExcelDeV(workOrderQuery.getBillType(), workOrderQuery.getWorkOrderNo(), drawingNumberList);
				} catch (InvalidPortException e) {
					e.printStackTrace();
				} catch (InvalidEndpointException e) {
					e.printStackTrace();
				}
			} else {
				// 采购清单 物料需求清单
				try {
					workOrderList = this.findAllLevelListDev(workOrderQuery.getBillType(), workOrderQuery.getWorkOrderNo(), drawingNumberList);
				} catch (InvalidPortException e) {
					e.printStackTrace();
				} catch (InvalidEndpointException e) {
					e.printStackTrace();
				}
			}
		}
		return workOrderList;
	}

	private List<DrawingWorkOrderVO> handleBomExcelDeV(Integer billNum, String wordOrderNo, List<String> bomDrawingNumber) throws InvalidPortException, InvalidEndpointException {
		List<DrawingInfo> drawingInfoList = drawingInfoService.list(new QueryWrapper<DrawingInfo>()
			.lambda()
			.in(DrawingInfo::getDrawingNumber, bomDrawingNumber));
		// 物料清单列表
		List<DrawingWorkOrderVO> wordOrderList = new ArrayList<>();
		Oss oss = ossBuilder.getOss(AuthUtil.getTenantId(), StringPool.EMPTY);
		MinioClient minioClient = new MinioClient(oss.getEndpoint(), oss.getAccessKey(), oss.getSecretKey());

		// 合并同类项使用，key: 代号+名称  value: 数量
		Map<Object, Integer> bomNumMap = new HashMap<>();

		for (DrawingInfo drawingInfo : drawingInfoList) {
			// 获取bom数据失败，不做操作
			if (drawingInfo == null) {
				return null;
			}
			Attach attach = attachService.getAttachByDrawingInfoId(drawingInfo.getId());
			// 附件为空，不做操作
			if (attach == null) {
				return null;
			}
			try {
				InputStream is = minioClient.getObject("000000-machtech", attach.getName());
				Workbook wb = excelUtils.getServerWb(attach.getName(), is);
				Sheet sheetAt = wb.getSheetAt(0);
				for (int j = 1; j <= sheetAt.getPhysicalNumberOfRows(); j++) {
					Row row = sheetAt.getRow(j);
					if (row == null) {
						continue;
					}
					if (excelUtils.checkRowError(row.getCell(1)) != 1) {
						continue;
					}
					String drawingNumber = excelUtils.getStringVal(row.getCell(1));
					String drawingName = excelUtils.getStringVal(row.getCell(2));
					String remark = row.getRowNum() > 8 ? excelUtils.getStringVal(row.getCell(8)) : null;
					// DrawingInfo drawingDetail = drawingInfoService.getDrawingInfo(drawingNumber, drawingName);
					DrawingInfo drawingDetail = null;
					if (StringUtil.isNotBlank(remark)) {
						drawingDetail = drawingInfoService.getOne(new QueryWrapper<DrawingInfo>()
							.lambda()
							.eq(DrawingInfo::getDrawingNumber, drawingNumber)
							.eq(DrawingInfo::getDrawingName, drawingName)
							.eq(DrawingInfo::getRemark, remark));
					} else {
						drawingDetail = drawingInfoService.getOne(new QueryWrapper<DrawingInfo>()
							.lambda()
							.eq(DrawingInfo::getDrawingNumber, drawingNumber)
							.eq(DrawingInfo::getDrawingName, drawingName));
					}
					if (drawingDetail == null) {
						continue;
					}
					//加工单生成单据时不带出系统图,除了系统图只生成第一行的，系统图生成第一行以下的(系统图04.05.06.07)，只生成本级
					if ((billNum == 1) && !drawingNumber.startsWith("MH")) {
						continue;
					} else if (billNum == 1 && (drawingNumber.split("\\.")[1].contains("04") || drawingNumber.split("\\.")[1].contains("05") ||
						drawingNumber.split("\\.")[1].contains("06") || drawingNumber.split("\\.")[1].contains("07"))) {
						continue;
					} else if (billNum == 1 && (!drawingNumber.split("\\.")[1].contains("04") && !drawingNumber.split("\\.")[1].contains("05")
						&& !drawingNumber.split("\\.")[1].contains("06") && !drawingNumber.split("\\.")[1].contains("07"))
						&& bomNumMap.size() > 0) {
						continue;
					} else if (billNum == 2 && StringUtil.isNotBlank(drawingDetail.getRemark()) && drawingDetail.getRemark().trim().equals("公用工程材料")) {
						continue;
					} else if (billNum == 3 && (StringUtil.isBlank(drawingDetail.getRemark()) || !drawingDetail.getRemark().trim().equals("公用工程材料"))) {
						continue;
					} else if (billNum == 4 && (StringUtil.isBlank(drawingDetail.getRemark()) || !drawingDetail.getRemark().trim().equals("系统材料"))) {
						continue;
					}
					// 封装加工清单或发货单信息
					handleDrawingBom(row, bomNumMap, wordOrderList, wordOrderNo);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return wordOrderList;
	}

	private List<DrawingWorkOrderVO> findAllLevelListDev(Integer billType, String workOrderNo, List<String> bomDrawingNumber) throws InvalidPortException, InvalidEndpointException {
		List<DrawingInfo> drawingInfoList = drawingInfoService.list(new QueryWrapper<DrawingInfo>()
			.lambda()
			.in(DrawingInfo::getDrawingNumber, bomDrawingNumber));
		// 合并同类项使用，key: 代号+名称  value: 数量
		Map<Object, Integer> bomNumMap = new HashMap<>();
		// 物料清单列表
		List<DrawingWorkOrderVO> wordOrderList = new ArrayList<>();
		Oss oss = ossBuilder.getOss(AuthUtil.getTenantId(), StringPool.EMPTY);
		MinioClient minioClient = new MinioClient(oss.getEndpoint(), oss.getAccessKey(), oss.getSecretKey());
		for (DrawingInfo drawingDetail : drawingInfoList) {
			// 获取bom数据失败，不做操作
			if (drawingDetail == null) {
				return null;
			}
			Attach attach = attachService.getAttachByDrawingInfoId(drawingDetail.getId());
			// 附件为空，不做操作
			if (attach == null) {
				return null;
			}
			try {

				InputStream is = minioClient.getObject("000000-machtech", attach.getName());
				Workbook wb = excelUtils.getServerWb(attach.getName(), is);
				Sheet sheetAt = wb.getSheetAt(0);
				for (int j = 1; j <= sheetAt.getPhysicalNumberOfRows(); j++) {
					Row row = sheetAt.getRow(j);
					if (row == null) {
						continue;
					}
					if (excelUtils.checkRowError(row.getCell(1)) != 1) {
						continue;
					}
					String drawingNumber = excelUtils.getStringVal(row.getCell(1));
					String drawingName = excelUtils.getStringVal(row.getCell(2));
					String bomSum = StringUtil.isNotBlank(excelUtils.getStringVal(row.getCell(3))) ? excelUtils.getStringVal(row.getCell(3)) : "1";
					String remark = row.getRowNum() > 8 ? excelUtils.getStringVal(row.getCell(8)) : null;
					if (StringUtil.isEmpty(drawingNumber) || StringUtil.isEmpty(drawingName)) {
						throw new ServiceException("上传的图纸存在异常!");
					}
					// DrawingInfo drawingInfo = drawingInfoService.getDrawingInfo(drawingNumber, drawingName);
					DrawingInfo drawingInfo = null;
					if (StringUtil.isNotBlank(remark)) {
						drawingInfo = drawingInfoService.getOne(new QueryWrapper<DrawingInfo>()
							.lambda()
							.eq(DrawingInfo::getDrawingNumber, drawingNumber)
							.eq(DrawingInfo::getDrawingName, drawingName)
							.eq(DrawingInfo::getRemark, remark));
					} else {
						drawingInfo = drawingInfoService.getOne(new QueryWrapper<DrawingInfo>()
							.lambda()
							.eq(DrawingInfo::getDrawingNumber, drawingNumber)
							.eq(DrawingInfo::getDrawingName, drawingName));
					}

					// 递归实现统计数量
					if (drawingInfo != null) {
						if ((billType == 5
							&& !drawingInfo.getDrawingNumber().startsWith("MH")
							&& !drawingInfo.getRemark().trim().equals("公用工程材料"))
							|| (billType == 6 && !drawingInfo.getDrawingNumber().startsWith("MH"))) {
							// 存在相同的数据先进行移除
							if (!Collections.isEmpty(wordOrderList)) {
								Iterator<DrawingWorkOrderVO> iterator = wordOrderList.iterator();
								while (iterator.hasNext()) {
									DrawingWorkOrderVO wordOrderVo = iterator.next();
									if (drawingInfo.getDrawingNumber().equals(wordOrderVo.getDrawingNumber())
										&& drawingInfo.getDrawingName().equals(wordOrderVo.getDrawingName())
										&& drawingInfo.getRemark().equals(wordOrderVo.getComment())) {
										iterator.remove();
									}
								}
							}
							// 设置Map key参数
							DrawingBomKey drawingBomKey = new DrawingBomKey();
							drawingBomKey.setDrawingNumber(drawingInfo.getDrawingNumber().trim());
							drawingBomKey.setDrawingName(drawingInfo.getDrawingName().trim());
							drawingBomKey.setRemark(drawingInfo.getRemark().trim());

							// 工单图纸信息
							DrawingWorkOrderVO drawingWordOrderVO = new DrawingWorkOrderVO();
							drawingWordOrderVO.setDrawingNumber(drawingInfo.getDrawingNumber());
							drawingWordOrderVO.setDrawingName(drawingInfo.getDrawingName());
							drawingWordOrderVO.setWorkOrderNo(workOrderNo);
							drawingWordOrderVO.setMaterial(drawingInfo.getMaterial());
							drawingWordOrderVO.setDrawingProperty(drawingInfo.getDrawingProperty());
							drawingWordOrderVO.setComment(drawingInfo.getRemark());
							drawingWordOrderVO.setCharacOne(drawingInfo.getCharacOne());
							drawingWordOrderVO.setCharacTwo(drawingInfo.getCharacTwo());
							drawingWordOrderVO.setCharacThree(drawingInfo.getCharacThree());
							if (StringUtil.isNotBlank(workOrderNo)) {
								QueryWrapper<ProjectMana> queryWrapper = Condition.getQueryWrapper(new ProjectMana());
								queryWrapper.lambda().eq(ProjectMana::getWorkOrderNo, workOrderNo);
								ProjectMana projectMana = projectManaService.getOne(queryWrapper);
								if (projectMana != null) {
									drawingWordOrderVO.setCustomerName(projectMana.getCustomerName());
									drawingWordOrderVO.setProjectName(projectMana.getProjectName());
								}
							}

							// 判断是否是从根节点进来的，是：直接保存数量，否：根据parentId查询保存数量
							int bomNum;
							if (bomNumMap.get(drawingBomKey) != null) {
								bomNum = Integer.parseInt(bomSum) + bomNumMap.get(drawingBomKey);
							} else {
								bomNum = Integer.parseInt(bomSum);
							}
							drawingWordOrderVO.setNum(bomNum);
							wordOrderList.add(drawingWordOrderVO);

							// map记录工单数量
							bomNumMap.put(drawingBomKey, bomNum);
						}
						List<DrawingInfoNode> drawingInfoNodeList = drawingInfoNodeService.findDrawingNodeList(drawingInfo.getId());
						if (!Collections.isEmpty(drawingInfoNodeList)) {
							BomExplosionbyLevel(billType, workOrderNo, Integer.parseInt(bomSum), drawingInfo, bomNumMap, wordOrderList);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
		return wordOrderList;
	}


	private List<DrawingWorkOrderVO> handleBomExcel(Integer billNum, String wordOrderNo, String bomDrawingNumber) {
		QueryWrapper<DrawingInfo> drawingInfoQuery = Condition.getQueryWrapper(new DrawingInfo());
		drawingInfoQuery.lambda().eq(DrawingInfo::getDrawingNumber, bomDrawingNumber);
		DrawingInfo drawingInfo = drawingInfoService.getOne(drawingInfoQuery);
		// 获取bom数据失败，不做操作
		if (drawingInfo == null) {
			return null;
		}
		Attach attach = attachService.getAttachByDrawingInfoId(drawingInfo.getId());
		// 附件为空，不做操作
		if (attach == null) {
			return null;
		}

		// 合并同类项使用，key: 代号+名称  value: 数量
		Map<Object, Integer> bomNumMap = new HashMap<>();
		// 物料清单列表
		List<DrawingWorkOrderVO> wordOrderList = new ArrayList<>();
		Oss oss = ossBuilder.getOss(AuthUtil.getTenantId(), StringPool.EMPTY);
		try {
			MinioClient minioClient = new MinioClient(oss.getEndpoint(), oss.getAccessKey(), oss.getSecretKey());
			InputStream is = minioClient.getObject("000000-machtech", attach.getName());
			Workbook wb = excelUtils.getServerWb(attach.getName(), is);
			Sheet sheetAt = wb.getSheetAt(0);
			for (int j = 1; j <= sheetAt.getPhysicalNumberOfRows(); j++) {
				Row row = sheetAt.getRow(j);
				if (row == null) {
					continue;
				}
				if (excelUtils.checkRowError(row.getCell(1)) != 1) {
					continue;
				}
				String drawingNumber = excelUtils.getStringVal(row.getCell(1));
				String drawingName = excelUtils.getStringVal(row.getCell(2));
				DrawingInfo drawingDetail = drawingInfoService.getDrawingInfo(drawingNumber, drawingName);
				if ((billNum == 1 || billNum == 2) && !drawingNumber.startsWith("MH")) {
					continue;
				} else if (billNum == 3 && !drawingDetail.getRemark().trim().equals("公用工程材料")) {
					continue;
				} else if (billNum == 4 && !drawingDetail.getRemark().trim().equals("系统材料")) {
					continue;
				}
				// 封装加工清单或发货单信息
				handleDrawingBom(row, bomNumMap, wordOrderList, wordOrderNo);
			}
			return wordOrderList;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return wordOrderList;
	}

	private void handleDrawingBom(Row row, Map<Object, Integer> bomNumMap, List<DrawingWorkOrderVO> wordOrderList, String wordOrderNo) {
		String drawingNumber = excelUtils.getStringVal(row.getCell(1));
		String drawingName = excelUtils.getStringVal(row.getCell(2));
		String bomSum = StringUtil.isNotBlank(excelUtils.getStringVal(row.getCell(3))) ? excelUtils.getStringVal(row.getCell(3)) : "1";
		String remark = row.getRowNum() > 8 ? excelUtils.getStringVal(row.getCell(8)) : null;

		if (StringUtil.isEmpty(drawingNumber) || StringUtil.isEmpty(drawingName)) {
			throw new ServiceException("上传的图纸存在异常!");
		}

//		DrawingInfo drawingInfo = drawingInfoService.getDrawingInfo(drawingNumber, drawingName);
		DrawingInfo drawingInfo = null;
		if (StringUtil.isNotBlank(remark)) {
			drawingInfo = drawingInfoService.getOne(new QueryWrapper<DrawingInfo>()
				.lambda()
				.eq(DrawingInfo::getDrawingNumber, drawingNumber)
				.eq(DrawingInfo::getDrawingName, drawingName)
				.eq(DrawingInfo::getRemark, remark));
		} else {
			drawingInfo = drawingInfoService.getOne(new QueryWrapper<DrawingInfo>()
				.lambda()
				.eq(DrawingInfo::getDrawingNumber, drawingNumber)
				.eq(DrawingInfo::getDrawingName, drawingName));
		}

		// 存在相同的数据先进行移除
		if (!Collections.isEmpty(wordOrderList)) {
			Iterator<DrawingWorkOrderVO> iterator = wordOrderList.iterator();
			while (iterator.hasNext()) {
				DrawingWorkOrderVO wordOrderVo = iterator.next();
				if (drawingInfo.getDrawingNumber().equals(wordOrderVo.getDrawingNumber())
					&& drawingInfo.getDrawingName().equals(wordOrderVo.getDrawingName())
					&& drawingInfo.getRemark().equals(wordOrderVo.getComment())) {
					iterator.remove();
				}
			}
		}
		// 设置Map key参数
		DrawingBomKey drawingBomKey = new DrawingBomKey();
		drawingBomKey.setDrawingNumber(drawingInfo.getDrawingNumber());
		drawingBomKey.setDrawingName(drawingInfo.getDrawingName());
		drawingBomKey.setRemark(drawingInfo.getRemark());

		// 工单图纸信息
		DrawingWorkOrderVO drawingWordOrderVO = new DrawingWorkOrderVO();
		drawingWordOrderVO.setDrawingNumber(drawingInfo.getDrawingNumber());
		drawingWordOrderVO.setDrawingName(drawingInfo.getDrawingName());
		drawingWordOrderVO.setMaterial(drawingInfo.getMaterial());
		drawingWordOrderVO.setDrawingProperty(drawingInfo.getDrawingProperty());
		drawingWordOrderVO.setComment(drawingInfo.getRemark());
		drawingWordOrderVO.setWorkOrderNo(wordOrderNo);
		drawingWordOrderVO.setCharacOne(drawingInfo.getCharacOne());
		drawingWordOrderVO.setCharacTwo(drawingInfo.getCharacTwo());
		drawingWordOrderVO.setCharacThree(drawingInfo.getCharacThree());

		if (StringUtil.isNotBlank(wordOrderNo)) {
			QueryWrapper<ProjectMana> queryWrapper = Condition.getQueryWrapper(new ProjectMana());
			queryWrapper.lambda().eq(ProjectMana::getWorkOrderNo, wordOrderNo);
			ProjectMana projectMana = projectManaService.getOne(queryWrapper);
			if (projectMana != null) {
				drawingWordOrderVO.setCustomerName(projectMana.getCustomerName());
				drawingWordOrderVO.setProjectName(projectMana.getProjectName());
			}
		}

		int bomNum;
		if (bomNumMap.get(drawingBomKey) != null) {
			bomNum = Integer.parseInt(bomSum) + bomNumMap.get(drawingBomKey);
		} else {
			bomNum = Integer.parseInt(bomSum);
		}
		drawingWordOrderVO.setNum(bomNum);
		wordOrderList.add(drawingWordOrderVO);

		// map记录工单数量
		bomNumMap.put(drawingBomKey, bomNum);
	}

	private List<DrawingWorkOrderVO> findAllLevelList(Integer billType, String workOrderNo, String bomDrawingNumber) {
		QueryWrapper<DrawingInfo> drawingInfoQuery = Condition.getQueryWrapper(new DrawingInfo());
		drawingInfoQuery.lambda().eq(DrawingInfo::getDrawingNumber, bomDrawingNumber);
		DrawingInfo drawingDetail = drawingInfoService.getOne(drawingInfoQuery);
		// 获取bom数据失败，不做操作
		if (drawingDetail == null) {
			return null;
		}
		Attach attach = attachService.getAttachByDrawingInfoId(drawingDetail.getId());
		// 附件为空，不做操作
		if (attach == null) {
			return null;
		}
		// 合并同类项使用，key: 代号+名称  value: 数量
		Map<Object, Integer> bomNumMap = new HashMap<>();
		// 物料清单列表
		List<DrawingWorkOrderVO> wordOrderList = new ArrayList<>();

		Oss oss = ossBuilder.getOss(AuthUtil.getTenantId(), StringPool.EMPTY);
		try {
			MinioClient minioClient = new MinioClient(oss.getEndpoint(), oss.getAccessKey(), oss.getSecretKey());
			InputStream is = minioClient.getObject("000000-machtech", attach.getName());
			Workbook wb = excelUtils.getServerWb(attach.getName(), is);
			Sheet sheetAt = wb.getSheetAt(0);
			for (int j = 1; j <= sheetAt.getPhysicalNumberOfRows(); j++) {
				Row row = sheetAt.getRow(j);
				if (row == null) {
					continue;
				}
				if (excelUtils.checkRowError(row.getCell(1)) != 1) {
					continue;
				}
				String drawingNumber = excelUtils.getStringVal(row.getCell(1));
				String drawingName = excelUtils.getStringVal(row.getCell(2));
				String bomSum = excelUtils.getStringVal(row.getCell(3));
				if (StringUtil.isEmpty(drawingNumber) || StringUtil.isEmpty(drawingName)) {
					throw new ServiceException("上传的图纸存在异常!");
				}
				DrawingInfo drawingInfo = drawingInfoService.getDrawingInfo(drawingNumber, drawingName);
				// 递归实现统计数量
				if (drawingInfo != null) {
					if ((billType == 5 && ("外购件").equals(drawingInfo.getRemark())) ||
						(billType == 6 && !drawingInfo.getDrawingNumber().startsWith("MH"))) {
						// 存在相同的数据先进行移除
						if (!Collections.isEmpty(wordOrderList)) {
							Iterator<DrawingWorkOrderVO> iterator = wordOrderList.iterator();
							while (iterator.hasNext()) {
								DrawingWorkOrderVO wordOrderVo = iterator.next();
								if (drawingInfo.getDrawingNumber().equals(wordOrderVo.getDrawingNumber()) && drawingInfo.getDrawingName().equals(wordOrderVo.getDrawingName())) {
									iterator.remove();
								}
							}
						}
						// 设置Map key参数
						DrawingBomKey drawingBomKey = new DrawingBomKey();
						drawingBomKey.setDrawingNumber(drawingInfo.getDrawingNumber());
						drawingBomKey.setDrawingName(drawingInfo.getDrawingName());

						// 工单图纸信息
						DrawingWorkOrderVO drawingWordOrderVO = new DrawingWorkOrderVO();
						drawingWordOrderVO.setDrawingNumber(drawingInfo.getDrawingNumber());
						drawingWordOrderVO.setDrawingName(drawingInfo.getDrawingName());
						drawingWordOrderVO.setWorkOrderNo(workOrderNo);
						drawingWordOrderVO.setMaterial(drawingInfo.getMaterial());
						drawingWordOrderVO.setDrawingProperty(drawingInfo.getDrawingProperty());
						drawingWordOrderVO.setComment(drawingInfo.getRemark());
						drawingWordOrderVO.setCharacOne(drawingInfo.getCharacOne());
						drawingWordOrderVO.setCharacTwo(drawingInfo.getCharacTwo());
						drawingWordOrderVO.setCharacThree(drawingInfo.getCharacThree());
						if (StringUtil.isNotBlank(workOrderNo)) {
							QueryWrapper<ProjectMana> queryWrapper = Condition.getQueryWrapper(new ProjectMana());
							queryWrapper.lambda().eq(ProjectMana::getWorkOrderNo, workOrderNo);
							ProjectMana projectMana = projectManaService.getOne(queryWrapper);
							if (projectMana != null) {
								drawingWordOrderVO.setCustomerName(projectMana.getCustomerName());
								drawingWordOrderVO.setProjectName(projectMana.getProjectName());
							}
						}

						// 判断是否是从根节点进来的，是：直接保存数量，否：根据parentId查询保存数量
						int bomNum;
						if (bomNumMap.get(drawingBomKey) != null) {
							bomNum = Integer.parseInt(bomSum) + bomNumMap.get(drawingBomKey);
						} else {
							bomNum = Integer.parseInt(bomSum);
						}
						drawingWordOrderVO.setNum(bomNum);
						wordOrderList.add(drawingWordOrderVO);

						// map记录工单数量
						bomNumMap.put(drawingBomKey, bomNum);
					}
					List<DrawingInfoNode> drawingInfoNodeList = drawingInfoNodeService.findDrawingNodeList(drawingInfo.getId());
					if (!Collections.isEmpty(drawingInfoNodeList)) {
						BomExplosionbyLevel(billType, workOrderNo, Integer.parseInt(bomSum), drawingInfo, bomNumMap, wordOrderList);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return wordOrderList;
	}

	private void BomExplosionbyLevel(Integer billType, String workOrderNo, Integer rootBomNum, DrawingInfo drawingInfo, Map<Object, Integer> bomNumMap, List<DrawingWorkOrderVO> wordOrderList) {

		// listBom 存放逐层展开 BOM的结果，初始获取第一层
		List<DrawingInfoNode> listBom = drawingInfoNodeService.findDrawingNodeList(drawingInfo.getId());

		// listBomt01 和listBomt02 交替逐层展开 BOM的临时两个 list 对象，并赋予初始值
		List<DrawingInfoNode> listBomt01 = drawingInfoNodeService.findDrawingNodeList(drawingInfo.getId());

		List<DrawingInfoNode> listBomt02 = new ArrayList<DrawingInfoNode>();
		// 开始逐层交替展开BOM，展开的每层BOM 节点要放入结果listBom 中，同时放入临时对象listBomt01 或
		// listBomt02中，等待继续循环往下展开，并且在放入之前临时对象要进行初始化

		for (DrawingInfoNode node : listBom) {
			int i = Integer.parseInt(node.getNum()) * rootBomNum;
			node.setNum(String.valueOf(i));
		}

		for (DrawingInfoNode node : listBomt01) {
			int i = Integer.parseInt(node.getNum()) * rootBomNum;
			node.setNum(String.valueOf(i));
		}

		while (listBomt01.size() > 0) {

			listBomt02.clear();
			// 当前层为listBomt01时结果输出至listBom 和listBomt02
			for (int i = 0; i < listBomt01.size(); i++) {
				DrawingInfoNode bom = listBomt01.get(i);
				Long subcode = bom.getChildId();
				Integer itemqty = Integer.parseInt(bom.getNum());
				List<DrawingInfoNode> listBomt01sub = drawingInfoNodeService.findDrawingNodeList(subcode);

				for (int i1 = 0; i1 < listBomt01sub.size(); i1++) {
					DrawingInfoNode bom1 = listBomt01sub.get(i1);
					Integer qty = Integer.parseInt(bom1.getNum());
					bom1.setNum(String.valueOf(qty * itemqty));
					listBom.add(bom1);
					listBomt02.add(bom1);
				}
			}

			listBomt01.clear();
			// 当前层为listBomt02时结果输出至listBom 和listBomt01
			for (int i = 0; i < listBomt02.size(); i++) {
				DrawingInfoNode bom = listBomt02.get(i);
				Long subcode = bom.getChildId();
				Integer itemqty = Integer.parseInt(bom.getNum());
				List<DrawingInfoNode> listBomt02sub = drawingInfoNodeService.findDrawingNodeList(subcode);

				for (int i2 = 0; i2 < listBomt02sub.size(); i2++) {
					DrawingInfoNode bom2 = listBomt02sub.get(i2);
					Integer qty = Integer.valueOf(bom2.getNum());
					bom2.setNum(String.valueOf(qty * itemqty));
					listBom.add(bom2);
					listBomt01.add(bom2);
				}
			}

		}

		// 返回展开的结果 listBom
		for (DrawingInfoNode drawingInfoNode : listBom) {
			DrawingInfo drawing = drawingInfoService.getById(drawingInfoNode.getChildId());
			if (drawing != null) {
				if ((billType == 5
					&& !drawing.getDrawingNumber().startsWith("MH")
					&& !drawing.getRemark().trim().equals("公用工程材料"))
					|| (billType == 6 && !drawing.getDrawingNumber().startsWith("MH"))) {
					// 存在相同的数据先进行移除
					if (!Collections.isEmpty(wordOrderList)) {
						Iterator<DrawingWorkOrderVO> iterator = wordOrderList.iterator();
						while (iterator.hasNext()) {
							DrawingWorkOrderVO wordOrderVo = iterator.next();
							if (drawing.getDrawingNumber().equals(wordOrderVo.getDrawingNumber())
								&& drawing.getDrawingName().equals(wordOrderVo.getDrawingName())
								&& drawing.getRemark().equals(wordOrderVo.getComment())) {
								iterator.remove();
							}
						}
					}
					// 设置Map key参数
					DrawingBomKey drawingBomKey = new DrawingBomKey();
					drawingBomKey.setDrawingNumber(drawing.getDrawingNumber().trim());
					drawingBomKey.setDrawingName(drawing.getDrawingName().trim());
					drawingBomKey.setRemark(drawing.getRemark().trim());

					// 工单图纸信息
					DrawingWorkOrderVO drawingWordOrderVO = new DrawingWorkOrderVO();
					drawingWordOrderVO.setDrawingNumber(drawing.getDrawingNumber());
					drawingWordOrderVO.setDrawingName(drawing.getDrawingName());
					drawingWordOrderVO.setWorkOrderNo(workOrderNo);
					drawingWordOrderVO.setMaterial(drawing.getMaterial());
					drawingWordOrderVO.setDrawingProperty(drawing.getDrawingProperty());
					drawingWordOrderVO.setComment(drawing.getRemark());
					drawingWordOrderVO.setCharacOne(drawing.getCharacOne());
					drawingWordOrderVO.setCharacTwo(drawing.getCharacTwo());
					drawingWordOrderVO.setCharacThree(drawing.getCharacThree());
					if (StringUtil.isNotBlank(workOrderNo)) {
						QueryWrapper<ProjectMana> queryWrapper = Condition.getQueryWrapper(new ProjectMana());
						queryWrapper.lambda().eq(ProjectMana::getWorkOrderNo, workOrderNo);
						ProjectMana projectMana = projectManaService.getOne(queryWrapper);
						if (projectMana != null) {
							drawingWordOrderVO.setCustomerName(projectMana.getCustomerName());
							drawingWordOrderVO.setProjectName(projectMana.getProjectName());
						}
					}

					// 判断是否是从根节点进来的，是：直接保存数量，否：根据parentId查询保存数量
					int bomNum;
					if (bomNumMap.get(drawingBomKey) != null) {
						bomNum = Integer.parseInt(drawingInfoNode.getNum()) + bomNumMap.get(drawingBomKey);
					} else {
						bomNum = Integer.parseInt(drawingInfoNode.getNum());
					}
					drawingWordOrderVO.setNum(bomNum);
					wordOrderList.add(drawingWordOrderVO);

					// map记录工单数量
					bomNumMap.put(drawingBomKey, bomNum);
				}
			}
		}
	}

	// 逐层展开统计 加工单下包含的MH开头的设备下 所有的零件有哪些
	private List<DrawingWorkOrderVO> getMaterailWeight() {

		return null;
	}


}
